import { useState, useEffect, useImperativeHandle, forwardRef } from 'react';
import { getMessage, TextWidget } from '@inbiz/react';
import { Button, Tag, message, Modal } from 'antd';
import api from '../SelectDoc/api';
import { useEvents } from '@inbiz/utils';
import type { inbiz } from '@inbiz/core';
import { DownOutlined } from '@ant-design/icons';
import '../SelectDoc/index.less';
import ModalData from './modelData';
import React from 'react';
import Container from '@inbiz/basic/container';

export type ModeType = 'SelectFolder' | 'SelectFile';

type IPorps = {
  mode: ModeType;
  isTpl: boolean;
  lang: string;
  value?: any;
  emit: any;
  inbiz: inbiz;
  callBackEvents?: {
    onBeforeOpen?: (type: string, data: any[]) => boolean | undefined;
    onBeforeClose?: (type: string, data: any[]) => boolean | undefined;
  };
  placeholder?: string;
  showPersonalLibrary?: boolean;
  multiple: boolean;
  defaultValue?: any;
  topFolder?: any;
  columnField: [];
  visibleModal: boolean;
  setVisibleModal: Function;
  selectNum: number;
  setSelectNum: Function;
  selectData: any[];
  setSelectData: Function;
  onChange: Function;
  selectFolderOrFile?: boolean;
  $value?: Function;
  accept?: { [key: string]: any }[];
  fileMode?: string;
  showTeam?: boolean;
  hidePersonalChildren?: boolean;
};

const SelectDocModal = forwardRef((props: IPorps, ref: any) => {
  const {
    mode,
    visibleModal,
    setVisibleModal,
    selectNum,
    setSelectNum,
    selectData,
    setSelectData,
    selectFolderOrFile,
    $value,
    accept,
    fileMode,
  } = props;

  const [configEvents] = useEvents<{
    onBeforeClose?: (type: string, data: any[]) => boolean | undefined;
  }>(props.callBackEvents, props.emit);

  useImperativeHandle(
    ref,
    () => ({
      ...api(configEvents),
      setSelectedRowKeys,
      setVisibleModal: (boolean: boolean) => {
        setVisibleModal(boolean);
      },
    }),
    [],
  );

  const [selectDatas, setSelectDatas] = useState<any[]>([]); //选中的数据
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]); //表格选中的行
  const [isShowSelectData, setIsShowSelectData] = useState<boolean>(false); //模态框是否显示选中数据

  const handleOk = async () => {
    let result = (await configEvents.current?.onBeforeClose?.('handleOk', selectDatas)) ?? true;

    if (!result) {
      return;
    }

    // 判断文件类型
    let corent: boolean = true;
    if (mode === 'SelectFile' && accept && fileMode) {
      for (let i = 0; i < selectDatas.length; i++) {
        const type = selectDatas[i].name.substring(selectDatas[i].name.lastIndexOf('.') + 1);
        if (accept?.length > 0) {
          if (fileMode === 'allow') {
            corent = accept.some((itme) => itme.type === type);
          } else {
            corent = !accept.some((itme) => itme.type === type);
          }
        }
        if (!corent) {
          message.destroy();
          message.error(
            `${fileMode === 'allow'
              ? getMessage('DocSelect.onlySupport')
              : getMessage('DocSelect.forbid')
            }${getMessage('DocSelect.select')}${accept
              .map((item) => item.type)
              .join('、')}${getMessage('DocSelect.fileType')}`,
          );
          return;
        }
      }
      if (!corent) {
        return;
      }
    }

    setVisibleModal(false);
    setIsShowSelectData(false);
    setSelectData(selectDatas);

    if (selectFolderOrFile) {
      if (selectDatas.length > 0) {
        $value && $value(selectDatas[0].name);
        props.onChange(
          selectDatas.map((item) => {
            return { ...item, id: item.key };
          }),
        );
      } else {
        $value && $value('');
        props.onChange([]);
      }
    } else {
      props.onChange(selectDatas);
    }

    props.emit?.('onClose', selectDatas);

    setSelectNum(selectDatas.length);
  };

  const handleCancel = async () => {
    let result = (await configEvents.current?.onBeforeClose?.('handleCancel', selectData)) ?? true;

    if (!result) {
      return;
    }

    props.emit?.('onClose', selectDatas);

    setVisibleModal(false);
    setSelectData([...selectData]);
    setIsShowSelectData(false);
    setSelectNum([...selectData].length);
    setSelectNum(selectData.length);
  };

  useEffect(() => {
    if (visibleModal && selectData?.length > 0) {
      setSelectDatas(selectData);
      setSelectedRowKeys(selectData?.map((v: any) => v.key));
    } else {
      setSelectDatas([]);
    }
  }, [selectData]);

  useEffect(() => {
    if (visibleModal) {
      setSelectDatas([...selectData]);
      setSelectNum([...selectData].length);
      setSelectedRowKeys(selectData.map((v) => v.key));
    }
  }, [visibleModal]);

  const closeData = async (item: any, index: number) => {
    let oldData = [...selectDatas];
    oldData.splice(index, 1);
    let oldSelectedRowKeys = [...selectedRowKeys];
    let num = oldSelectedRowKeys.findIndex((v) => v === item.key);
    oldSelectedRowKeys.splice(num, 1);
    setSelectedRowKeys(oldSelectedRowKeys);
    setSelectDatas(oldData);
    setSelectNum(oldData.length);
  };

  const modalataRef = React.createRef<any>();

  return (
    <Container>
      <Modal
        visible={visibleModal}
        title={
          mode === 'SelectFile'
            ? getMessage('DocSelect.selectFile')
            : getMessage('DocSelect.selectFolder')
        }
        width={800}
        style={{ height: 560 }}
        maskClosable={false}
        keyboard={false}
        onCancel={handleCancel}
        destroyOnClose
        className="inbizSeletDocModel"
        footer={[
          <div
            className="footerBox"
            style={{ height: isShowSelectData ? 80 : 0, marginBottom: 0 }}
            key={'selectData'}
          >
            {isShowSelectData && selectDatas?.length > 0
              ? selectDatas.map((item, index) => (
                <div className="tagClose" key={item.key}>
                  <Tag
                    closable
                    onClose={() => closeData(item, index)}
                    title={item.name}
                    style={{ color: 'var(--inbiz-color-heading)' }}
                  >
                    {item.name.length > 25 ? `${item.name.substr(0, 25)}...` : item.name}
                  </Tag>
                </div>
              ))
              : null}
          </div>,
          <span
            className="selectNum"
            key={'selectNum'}
            style={{ color: 'var(--inbiz-color-heading)' }}
          >
            <TextWidget>DocSelect.selectedNumber</TextWidget>：
            <span style={{ color: 'var(--inbiz-color-primary)' }}>{selectNum}</span>
            <DownOutlined
              className={isShowSelectData ? 'downIcon' : 'upIcon'}
              onClick={() => setIsShowSelectData(!isShowSelectData)}
            />
          </span>,
          <Button
            onClick={handleCancel}
            key="cancelModal"
            style={{ color: 'var(--inbiz-color-text)' }}
          >
            <TextWidget>DocSelect.cancelText</TextWidget>
          </Button>,
          <Button type="primary" onClick={handleOk} key="okModal">
            <TextWidget>DocSelect.okText</TextWidget>
          </Button>,
        ]}
      >
        <ModalData
          {...props}
          ref={modalataRef}
          selectDatas={selectDatas}
          setSelectDatas={setSelectDatas}
          isShowSelectData={isShowSelectData}
          selectedRowKeys={selectedRowKeys}
          setSelectedRowKeys={setSelectedRowKeys}
        />
      </Modal>
    </Container>
  );
});

export default SelectDocModal;
export type { api as selectApi };
